package com.mini.mybatis.mapping;

import com.mini.mybatis.session.Configuration;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 绑定SQL - 封装绑定的SQL语句和参数信息
 */
public class BoundSql {
    
    private final String sql;
    private final List<ParameterMapping> parameterMappings;
    private final Object parameterObject;
    private final Map<String, Object> additionalParameters;
    
    public BoundSql(Configuration configuration, String sql, List<ParameterMapping> parameterMappings, Object parameterObject) {
        this.sql = sql;
        this.parameterMappings = parameterMappings;
        this.parameterObject = parameterObject;
        this.additionalParameters = new HashMap<>();
    }
    
    /**
     * 获取SQL语句
     */
    public String getSql() {
        return sql;
    }
    
    /**
     * 获取参数映射列表
     */
    public List<ParameterMapping> getParameterMappings() {
        return parameterMappings;
    }
    
    /**
     * 获取参数对象
     */
    public Object getParameterObject() {
        return parameterObject;
    }
    
    /**
     * 是否有额外参数
     */
    public boolean hasAdditionalParameter(String name) {
        String paramName = new PropertyTokenizer(name).getName();
        return additionalParameters.containsKey(paramName);
    }
    
    /**
     * 设置额外参数
     */
    public void setAdditionalParameter(String name, Object value) {
        additionalParameters.put(name, value);
    }
    
    /**
     * 获取额外参数
     */
    public Object getAdditionalParameter(String name) {
        return additionalParameters.get(name);
    }
    
    /**
     * 简化版属性标记解析器
     */
    private static class PropertyTokenizer {
        private String name;
        
        public PropertyTokenizer(String fullname) {
            int delim = fullname.indexOf('.');
            if (delim > -1) {
                name = fullname.substring(0, delim);
            } else {
                name = fullname;
            }
        }
        
        public String getName() {
            return name;
        }
    }
}